# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 13:58
# @Author  : CHNJX
# @File    : coordinate.py
# @Desc    :

from flask import Blueprint, request
from app.model import Coordinate, db
from app.utils.response_handler import response_with_handler, success_response, error_response

coordinate_bp = Blueprint('coordinate', __name__)


@coordinate_bp.route('/module/<int:module_id>', methods=['GET'])
@response_with_handler
def get_coordinates_by_module(module_id):
    """获取指定模块的所有控件坐标"""
    coordinates = Coordinate.query.filter_by(module_id=module_id).all()
    return success_response([coord.to_dict() for coord in coordinates])


@coordinate_bp.route('/<int:coordinate_id>', methods=['GET'])
@response_with_handler
def get_coordinate(coordinate_id):
    """获取单个控件坐标"""
    coordinate = Coordinate.query.get(coordinate_id)
    if coordinate is None:
        return error_response("控件坐标不存在", code=404)
    return success_response(coordinate.to_dict())


@coordinate_bp.route('/', methods=['POST'])
@response_with_handler
def create_coordinate():
    """创建控件坐标"""
    data = request.get_json()
    required_fields = ['element_name', 'module_id', 'x_coord', 'y_coord']
    if not data or not all(field in data for field in required_fields):
        return error_response(f"缺少必要的参数: {', '.join(required_fields)}", code=400)

    coordinate = Coordinate.create_coordinate(data)
    return success_response(coordinate.to_dict(), "控件坐标创建成功")


@coordinate_bp.route('/<int:coordinate_id>', methods=['PUT'])
@response_with_handler
def update_coordinate(coordinate_id):
    """更新控件坐标"""
    coordinate = Coordinate.query.get(coordinate_id)
    if coordinate is None:
        return error_response("控件坐标不存在", code=404)

    data = request.get_json()
    updated_coordinate = coordinate.update_coordinate(data)
    return success_response(updated_coordinate.to_dict(), "控件坐标更新成功")


@coordinate_bp.route('/<int:coordinate_id>', methods=['DELETE'])
@response_with_handler
def delete_coordinate(coordinate_id):
    """删除控件坐标"""
    coordinate = Coordinate.query.get(coordinate_id)
    if coordinate is None:
        return error_response("控件坐标不存在", code=404)

    try:
        db.session.delete(coordinate)
        db.session.commit()
        return success_response(message="控件坐标删除成功")
    except Exception as e:
        db.session.rollback()
        return error_response(f"删除失败: {str(e)}", code=500)


@coordinate_bp.route('/batch', methods=['POST'])
@response_with_handler
def batch_create_coordinates():
    """批量创建控件坐标"""
    data = request.get_json()
    if not isinstance(data, list):
        return error_response("请求数据必须是数组格式", code=400)

    created_coordinates = []
    for item in data:
        required_fields = ['element_name', 'module_id', 'x_coord', 'y_coord']
        if not all(field in item for field in required_fields):
            return error_response(f"每个坐标都必须包含以下字段: {', '.join(required_fields)}", code=400)

        try:
            coordinate = Coordinate.create_coordinate(item)
            created_coordinates.append(coordinate.to_dict())
        except Exception as e:
            return error_response(f"创建坐标失败: {str(e)}", code=500)

    return success_response(created_coordinates, "批量创建控件坐标成功")